//
//  PVDDetailBottomView.swift
//  GreenDeal
//
//  Created by Moennig Q on 26/12/2022.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
class JobDetailSystemInfoView: CustomBackView {
    fileprivate lazy var disposeBag = DisposeBag()
    let topImageView = UIImageView()
    var spvView: UIView!
    let stcsLabel = PaddingLabel()
    let editSystemInfoBtn = ContentLabel(R.font.interMedium(size: 15),hexStr: "#A9ABADFF")
    let panelTableView = UITableView()
    let inverterTableView = UITableView()
    let batteryTableView = UITableView()
    //contraint
    var panelTableViewHeightConstraint: Constraint?
    var inverterTableViewHeightConstraint: Constraint?
    var batteryTableViewHeightConstraint: Constraint?
    let panelMoreImageView = ViewFactory.shared.generateMoreImageView()
    let inverterMoreImageView = ViewFactory.shared.generateMoreImageView()
    let batteryMoreImageView = ViewFactory.shared.generateMoreImageView()
    
    override func setUpView() {
        //topImageView
        topImageView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        topImageView.backgroundColor = UIColor(hexStr: "#70798A")
        topImageView.image = R.image.jobdetail_systeminfo_top_icon()
        topImageView.contentMode = .scaleAspectFit
        self.addSubview(topImageView)
        topImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
        //spvLabel
        spvView = self.getSPVView()
        self.addSubview(spvView)
        spvView.snp.makeConstraints { make in
            make.top.equalTo(topImageView.snp.bottom).offset(Constant.AllOutMargin)
            make.left.equalTo(Constant.AllOutMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //stcsLabel
        stcsLabel.backgroundColor = UIColor(hexStr: "#F5F5F5FF")
        stcsLabel.layer.cornerRadius = 15
        stcsLabel.setFont(R.font.interMedium(size: 13))
        stcsLabel.clipsToBounds = true
        self.addSubview(stcsLabel)
        stcsLabel.snp.makeConstraints { make in
            make.top.equalTo(spvView)
            make.left.equalTo(spvView.snp.right).offset(8)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //edit btn
        editSystemInfoBtn.text = "Edit"
        editSystemInfoBtn.textAlignment = .right
        self.addSubview(editSystemInfoBtn)
        editSystemInfoBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.width.greaterThanOrEqualTo(40)
            make.height.equalTo(40)
            make.centerY.equalTo(stcsLabel)
        }
        //panel tableview cell
        self.addSubview(panelTableView)
        panelTableView.snp.makeConstraints { make in
            make.top.equalTo(editSystemInfoBtn.snp.bottom)
            make.left.equalTo(spvView)
            make.right.equalTo(editSystemInfoBtn)
            self.panelTableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
        }
        //panel的more箭头
        self.addSubview(panelMoreImageView)
        panelMoreImageView.snp.makeConstraints { make in
            make.top.equalTo(panelTableView).offset(CREATEJOB_REVIEW_INTERNAL)
            make.right.equalTo(panelTableView)
            make.width.height.equalTo(24)
        }
        //inverter tableview cell
        self.addSubview(inverterTableView)
        inverterTableView.snp.makeConstraints { make in
            make.top.equalTo(panelTableView.snp.bottom).offset(CREATEJOB_REVIEW_INTERNAL / 2)
            make.left.right.equalTo(panelTableView)
            self.inverterTableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
        }
        //inverter的more箭头
        self.addSubview(inverterMoreImageView)
        inverterMoreImageView.snp.makeConstraints { make in
            make.top.equalTo(inverterTableView).offset(CREATEJOB_REVIEW_INTERNAL)
            make.right.equalTo(inverterTableView)
            make.width.height.equalTo(panelMoreImageView)
        }
        //battery tableview cell
        self.addSubview(batteryTableView)
        batteryTableView.snp.makeConstraints { make in
            make.top.equalTo(inverterTableView.snp.bottom).offset(CREATEJOB_REVIEW_INTERNAL / 2)
            make.left.right.equalTo(panelTableView)
            self.batteryTableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
            make.bottom.equalToSuperview()
        }
        //battery的more箭头
        self.addSubview(batteryMoreImageView)
        batteryMoreImageView.snp.makeConstraints { make in
            make.top.equalTo(batteryTableView).offset(CREATEJOB_REVIEW_INTERNAL)
            make.right.equalTo(batteryTableView)
            make.width.height.equalTo(panelMoreImageView)
        }
        panelTableView.separatorStyle = .none
        inverterTableView.separatorStyle = .none
        batteryTableView.separatorStyle = .none
        panelTableView.register(JobDetailPanelTableViewCell.self, forCellReuseIdentifier: JobDetailPanelTableViewCell.reuseCellIdentifier)
        inverterTableView.register(JobDetailInverterTableViewCell.self, forCellReuseIdentifier: JobDetailInverterTableViewCell.reuseCellIdentifier)
        batteryTableView.register(JobDetailBatteryTableViewCell.self, forCellReuseIdentifier: JobDetailBatteryTableViewCell.reuseCellIdentifier)
        
        //监听属性变化
        panelTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.panelTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //监听属性变化
        inverterTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.inverterTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //监听属性变化
        batteryTableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.batteryTableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //
        self.bindData()
    }
    private func bindData(){
        self.editSystemInfoBtn.isHidden = !JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag
        //SPV check
        JobDetailModelHelper.shared.spv_check.subscribe(onNext: { [weak self] (flag) in
            guard let strongSelf = self else {return}
            if flag {//
                strongSelf.spvView.isHidden = false
                strongSelf.stcsLabel.snp.remakeConstraints { make in
                    make.top.equalTo(strongSelf.spvView)
                    make.left.equalTo(strongSelf.spvView.snp.right).offset(8)
                    make.height.width.greaterThanOrEqualTo(0)
                }
            }else{
                strongSelf.spvView.isHidden = true
                strongSelf.stcsLabel.snp.remakeConstraints { make in
                    make.top.equalTo(strongSelf.spvView)
                    make.left.equalTo(16)
                    make.height.width.greaterThanOrEqualTo(0)
                }
            }
        }).disposed(by: self.disposeBag)
        //stcs
        JobDetailModelHelper.shared.system_detail.map({$0.rec_quantity}).subscribe(onNext: { [weak self] (data) in
            guard let strongSelf = self else {return}
            strongSelf.stcsLabel.attributedText = strongSelf.getStcsAttributeString(data)
        }).disposed(by: self.disposeBag)
        //设置cell信息，panels绑定数据源
        JobDetailModelHelper.shared.system_detail.map({$0.panels}).bind(to: panelTableView.rx.items(cellIdentifier: JobDetailPanelTableViewCell.reuseCellIdentifier,cellType: JobDetailPanelTableViewCell.self)){(row, model, cell) in
            cell.setData(model,index: row)
        }.disposed(by: self.disposeBag)
        //设置cell信息，inverters绑定数据源
        JobDetailModelHelper.shared.system_detail.map({$0.inverters}).bind(to: inverterTableView.rx.items(cellIdentifier: JobDetailInverterTableViewCell.reuseCellIdentifier,cellType: JobDetailInverterTableViewCell.self)){(row, model, cell) in
            cell.setData(model,index: row)
        }.disposed(by: self.disposeBag)
        //设置cell信息，batterys绑定数据源
        JobDetailModelHelper.shared.system_detail.map({$0.batteries}).bind(to: batteryTableView.rx.items(cellIdentifier: JobDetailBatteryTableViewCell.reuseCellIdentifier,cellType: JobDetailBatteryTableViewCell.self)){(row, model, cell) in
            cell.setData(model,index: row)
        }.disposed(by: self.disposeBag)
        
    }
    //MARK: - 是否显示panel，inverter ，battery tableview右上角的接头（显示表示可以编辑）,以及整个system的edit 按钮
    func checkIfShowMoreImageView(){
        self.editSystemInfoBtn.isHidden = !JobDetailModelHelper.shared.jobDetailModel.canEditPanelInfoFlag
        let panelSCnt = JobDetailModelHelper.shared.jobDetailModel.system_detail.panels.count
        if  JobDetailModelHelper.shared.jobDetailModel.canEditPanelInfoFlag && panelSCnt > 0 {
            self.panelMoreImageView.isHidden = false
        }else{
            self.panelMoreImageView.isHidden = true
        }
        if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag {//installer角色且有数据才显示
            self.inverterMoreImageView.isHidden = JobDetailModelHelper.shared.jobDetailModel.system_detail.inverters.count > 0 ? false : true
            self.batteryMoreImageView.isHidden = JobDetailModelHelper.shared.jobDetailModel.system_detail.batteries.count > 0 ? false : true
        }else{
            self.inverterMoreImageView.isHidden = true
            self.batteryMoreImageView.isHidden = true
        }
    }
    private func getStcsAttributeString(_ stcs: String)->NSMutableAttributedString{
        let firstStr = "STCs "
        var secStr = stcs
        if let data = Int(stcs) {
            let formatStcs = Tool().formatAmountToStr(amount: stcs, maximumFractionDigits: 0,minimumFractionDigits: 0)
            secStr = formatStcs
        }
        
        let attrString = NSMutableAttributedString(string: firstStr + secStr)
        let strSubAttr1: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#292D32FF")]
        let strSubAttr2: [NSMutableAttributedString.Key: Any] = [.foregroundColor: UIColor(hexStr: "#379657FF")]
        attrString.addAttributes(strSubAttr1, range: NSRange(location: 0, length: firstStr.count))
        attrString.addAttributes(strSubAttr2, range: NSRange(location: firstStr.count, length: secStr.count))
        return attrString
    }
    private func getSPVView()->UIView{
        let view = UIView()
        view.drawCorner(byRoundingCorners: .allCorners,radii: 15, backColorHexStr: "#F5F5F5")
        //spvLabel
        let spvLabel = ContentLabel(R.font.interMedium(size: 13))
        spvLabel.text = "SPV"
        view.addSubview(spvLabel)
        spvLabel.snp.makeConstraints { make in
            make.top.equalTo(4)
            make.left.equalTo(8)
            make.height.width.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-4)
        }
        //tip Image
        let tipImageView = UIImageView(image: R.image.installation_detail_spv_tip_icon())
        view.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.left.equalTo(spvLabel.snp.right).offset(4)
            make.right.equalTo(-8)
            make.height.width.equalTo(16)
            make.centerY.equalToSuperview()
        }
        return view
    }
}
